Page({
  data: {
    loading: false,
    username: ''
  },
  onLoad: function() {
    var username = wx.getStorageSync('username');
    if (username) {
      this.setData({
        username: username
      });
    }
    console.log('username:', username)
  },

  submitForm(e) {
    const { oldPassword, newPassword, confirmPassword } = e.detail.value
    
    if (!this.validateForm(oldPassword, newPassword, confirmPassword)) return
    
    this.setData({ loading: true })
    
    // 调用修改密码接口
    wx.request({
      url: 'http://192.168.172.134:5000/api/changepassword',
      method: 'GET',
      data: {
        username: this.data.username,
        oldPassword,
        newPassword
      },
      success: (res) => {
        if (res.data.code === 200) {
          wx.showToast({
            title: '修改成功',
            icon: 'success'
          })
          setTimeout(() => {
            wx.navigateBack()
          }, 1500)
        } else {
          wx.showToast({
            title: res.data.msg || '修改失败',
            icon: 'none'
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        })
      },
      complete: () => {
        this.setData({ loading: false })
      }
    })
  },

  validateForm(oldPwd, newPwd, confirmPwd) {
    if (!oldPwd) {
      wx.showToast({ title: '请输入旧密码', icon: 'none' })
      return false
    }
    if (!newPwd || newPwd.length < 6) {
      wx.showToast({ title: '新密码至少6位', icon: 'none' })
      return false
    }
    if (newPwd !== confirmPwd) {
      wx.showToast({ title: '两次输入密码不一致', icon: 'none' })
      return false
    }
    return true
  }
})